#define _XOPEN_SOURCE
#include <func.h>
#include "head.h"
#define SALT_LEN 12
int createSalt(char salt[]){
    int i, flag;
    srand(time(NULL));
    char arr[SALT_LEN - 4];
    for(i = 0; i < SALT_LEN - 4; i++){
        flag = rand()%3;
        switch(flag){
            case 0:
                arr[i] = rand()%26 + 'a';
                break;
            case 1:
                arr[i] = rand()%26 + 'A';
                break;
            case 2:
                arr[i] = rand()%10 + '0';
                break;
        }
    }
    sprintf(salt, "$6$%s$", arr);
}

/*待处理注册重名时的情况*/
int userRegister(MYSQL *db, char *userName, char *saltForToken, char *token, int netFd){
    int dataLength;
    char password[100] = {0};
    recv(netFd, &dataLength, sizeof(dataLength), MSG_WAITALL);
    recv(netFd, password, dataLength, MSG_WAITALL);

    makeToken(saltForToken, userName, token);
    // printf("token = %s\n", token);
    /*send token*/
    train_t t;
    strcpy(t.buf, token);
    t.dataLength = strlen(t.buf);
    send(netFd, &t, sizeof(t.dataLength)+t.dataLength, MSG_NOSIGNAL);
    
    char salt[SALT_LEN + 1] = {0};
    createSalt(salt);
    char cryptograph[500] = {0};
    strcpy(cryptograph,crypt(password, salt)); //crypt(密码，盐值);

    int ret = insertNewUser(db, userName, salt, cryptograph);
    if(ret == -1){
        puts("duplicated name");
    }else{
        insertNewUserRootDir(db, userName);
    }
}